﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Text;
using System.Windows;
using SqlSugar;


namespace DSFramework
{
    public class SQL
    {
        private static string CurrConStr = "";
        static DbType dbType = DbType.MySql;

        public static void InitSQL(string server, string database, string userid, string password, string databaseStr = "", int port=-1)
        {
            try
            {
                switch (databaseStr)
                {
                    case "MySql":
                        dbType = DbType.MySql;
                        CurrConStr = $"server={server};port={port};user={userid};password={password}; database={database};";
                        break;
                    case "SqlServer":
                        dbType = DbType.SqlServer;
                        CurrConStr = $"data source={server};initial catalog={database};user id={userid};password={password};";
                        break;
                    case "PostgreSQL":
                        dbType = DbType.PostgreSQL;
                        CurrConStr = $"PORT={port};DATABASE={database};HOST={server};PASSWORD={password};USER ID={userid}";
                        break;
                    case "SQLite":
                        dbType = DbType.Sqlite;
                        CurrConStr = @$"Data Source={database}";
                        break;
                    default:
                        UtilitieTools.Log($"Support Database are [ MySql , SqlServer , PostgreSQL ]", "", UtilitieTools.LogType.Error);
                        return;
                }

                UtilitieTools.Log($"SQL SERVICE IS STARTING ...", "", UtilitieTools.LogType.Info);
                return;
            }
            catch (Exception ex)
            {
                UtilitieTools.Log($"{ex}", "InitSQL()");
                //throw new Exception("无法连接到数据库！");
                return;
            }
        }

        public static void ClosesSQL()
        {
            try
            {
                DB.Close();
            }
            catch (Exception ex)
            {
                UtilitieTools.Log($"{ex}", "ClosesSQL()");
            }
        }

        static readonly object lock_db = new object();
        static SqlSugarClient db = null;

        /// <summary>
        /// 创建数据库连接
        /// </summary>
        public static SqlSugarClient DB
        {
            get
            {
                try
                {
                    if (db == null)
                    {
                        lock (lock_db)
                        {
                            if (db == null)
                            {
                                //创建数据库对象
                                SqlSugarClient db = new SqlSugarClient(new ConnectionConfig
                                {
                                    ConnectionString = CurrConStr, //连接符字串
                                    DbType = dbType,
                                    IsAutoCloseConnection = true,
                                    InitKeyType = InitKeyType.Attribute, //从特性读取主键自增信息
                                    MoreSettings = new ConnMoreSettings()
                                    {
                                        PgSqlIsAutoToLower = false //数据库存在大写字段的 ，需要把这个设为false ，并且实体和字段名称要一样
                                    },
                                });
                                db.Ado.CommandTimeOut = 30; //单位秒

                                return db;
                            }
                        }
                    }
                    else
                    {
                        return db;
                    }
                }
                catch (Exception ex)
                {
                    UtilitieTools.Log($"{ex.ToString()}", "DB");
                }

                return new SqlSugarClient(new ConnectionConfig());
            }
        }

        /// <summary>
        /// 创建数据库和表
        /// </summary>
        /// <param name="databaseName"></param>
        /// <param name="tableEntity"></param>
        public static void CreateNewDataBaseAndTables(params Type[] tableEntitys)
        {
            try
            {
                DB.DbMaintenance.CreateDatabase();
                DB.CodeFirst.SetStringDefaultLength(200).InitTables(tableEntitys);
                GC.Collect();
            }
            catch (Exception ex)
            {
                UtilitieTools.Log($"{ex.ToString()}", "CreateNewDataBaseAndTables()");
            }
        }

        /// <summary>
        /// 生成实体
        /// </summary>
        public static void GenerateEntity()
        {
            try
            {
                string[] tables = { "CsdnBlogInfo" };

                foreach (var item in DB.DbMaintenance.GetTableInfoList())
                {
                    string entityName = item.Name.ToUpper();
                    DB.MappingTables.Add(entityName, item.Name);
                    foreach (var col in DB.DbMaintenance.GetColumnInfosByTableName(item.Name))
                    {
                        DB.MappingColumns.Add(col.DbColumnName , col.DbColumnName, entityName);
                    }
                }

                //DB.DbFirst.IsCreateAttribute().CreateClassFile(
                //    @"D:\zj_Programs\C#file\Console\GetWebsite\GetWebsite.Core\Models\",
                //    "GetWebsite");

                DB.DbFirst.Where(tables).IsCreateAttribute().CreateClassFile(
                @"D:\zj_Programs\C#file\Console\GetWebsite\GetWebsite.Core\Models\",
                    "GetWebsite");
            }
            catch (Exception ex)
            {
                UtilitieTools.Log($"{ex.ToString()}", "GenerateEntity()");
            }
        }
    }
}